package com.nari.ncps.screen.service.impl.dryport;

import cn.hutool.core.bean.BeanUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.nari.ncps.screen.entity.dryport.DryportProdoperOwnCoal;
import com.nari.ncps.screen.entity.dryport.DryportProdoperTurnover;
import com.nari.ncps.screen.mapper.dryport.DryportProdoperTurnoverMapper;
import com.nari.ncps.screen.service.dryport.DryportProdoperTurnoverService;
import com.nari.ncps.screen.vo.dryport.OwnCoalVO;
import com.nari.ncps.screen.vo.dryport.TurnoverVO;
import com.nari.ncps.screen.vo.wholeproduct.GoodsTurnoverVO;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.math.RoundingMode;
import java.time.LocalDate;
import java.time.format.DateTimeFormatter;
import java.util.ArrayList;
import java.util.Comparator;
import java.util.List;
import java.util.stream.Collectors;

/**
 * <p>
 * 周转计划情况表 服务实现类
 * </p>
 *
 * @author xuesong
 * @since 2025-08-23
 */
@Service
public class DryportProdoperTurnoverServiceImpl extends ServiceImpl<DryportProdoperTurnoverMapper, DryportProdoperTurnover> implements DryportProdoperTurnoverService {

    @Autowired
    private DryportProdoperTurnoverMapper dryportProdoperTurnoverMapper;

    @Override
    public List<TurnoverVO> getMonthlyStatsByYear(Integer year) {
        List<DryportProdoperTurnover> entityList;

        // 如果year为null，获取最新的月度数据；否则根据年份查询
        if (year == null) {
            entityList = baseMapper.getLatestMonthlyStats();
        } else {
            entityList = baseMapper.getMonthlyStatsByYear(year);
        }

        // 转换为VO对象
        return entityList.stream().map(entity -> {
            TurnoverVO vo = new TurnoverVO();
            BeanUtils.copyProperties(entity, vo);
            return vo;
        }).collect(Collectors.toList());
    }

    @Override
    public List<GoodsTurnoverVO> getGoodsTurnoverAnnual(Integer year) {
        List<GoodsTurnoverVO> resultList = new ArrayList<>();
//TODO 以下代码为应急新增，后期真数据进来再改
//        LambdaQueryWrapper<DryportProdoperTurnover> query = new LambdaQueryWrapper<>();
//        query.eq(DryportProdoperTurnover::getOrgCode, "100360")
//                .eq(DryportProdoperTurnover::getDateType, 0);
//        List<DryportProdoperTurnover> dataList = this.list(query);
//        for (DryportProdoperTurnover data : dataList) {
//            GoodsTurnoverVO vo = new GoodsTurnoverVO();
//            vo.setYear(data.getYear());
//            vo.setTurnoverPlanned(data.getTurnoverPlanned());
//            vo.setTurnoverCompleted(data.getTurnoverCompleted());
//            vo.setYoyRate(data.getCompletionRate());
//            resultList.add(vo);
//        }
        // 获取当前年份
        int currentYear = LocalDate.now().getYear();
        int currentMonth = LocalDate.now().getMonthValue();

        // 查询最近5年的数据
        for (int i = 4; i >= 0; i--) {
            int targetYear = currentYear - i;

            // 查询目标年份的所有月份数据
            LambdaQueryWrapper<DryportProdoperTurnover> query = new LambdaQueryWrapper<>();
            query.eq(DryportProdoperTurnover::getYear, targetYear);

            // 如果是当前年份，只查询到当前月份
            if (targetYear == currentYear) {
                query.le(DryportProdoperTurnover::getMonth, currentMonth);
            }

            List<DryportProdoperTurnover> yearDataList = this.list(query);

            if (!yearDataList.isEmpty()) {
                GoodsTurnoverVO vo = new GoodsTurnoverVO();
                vo.setYear(targetYear);

                // 汇总年度计划量和完成量（累加各月数据）
                BigDecimal totalPlanned = yearDataList.stream()
                        .map(DryportProdoperTurnover::getTurnoverPlanned)
                        .filter(planned -> planned != null)
                        .reduce(BigDecimal.ZERO, BigDecimal::add);

                BigDecimal totalCompleted = yearDataList.stream()
                        .map(DryportProdoperTurnover::getTurnoverCompleted)
                        .filter(completed -> completed != null)
                        .reduce(BigDecimal.ZERO, BigDecimal::add);

                vo.setTurnoverPlanned(totalPlanned.setScale(2, RoundingMode.HALF_UP));
                vo.setTurnoverCompleted(totalCompleted.setScale(2, RoundingMode.HALF_UP));

//                 计算同比率：需要去年同期的完成量
                int lastYear = targetYear - 1;
                LambdaQueryWrapper<DryportProdoperTurnover> lastYearQuery = new LambdaQueryWrapper<>();
                lastYearQuery.eq(DryportProdoperTurnover::getYear, lastYear);

                // 如果是当前年份，去年也只查询到对应的月份
                if (targetYear == currentYear) {
                    lastYearQuery.le(DryportProdoperTurnover::getMonth, currentMonth);
                }

                List<DryportProdoperTurnover> lastYearDataList = this.list(lastYearQuery);

                if (!lastYearDataList.isEmpty()) {
                    BigDecimal lastYearCompleted = lastYearDataList.stream()
                            .map(DryportProdoperTurnover::getTurnoverCompleted)
                            .filter(completed -> completed != null)
                            .reduce(BigDecimal.ZERO, BigDecimal::add);

                    // 同比率(%) = (今年完成量 - 去年完成量) / 去年完成量 * 100
                    if (lastYearCompleted.compareTo(BigDecimal.ZERO) > 0) {
                        BigDecimal yoyRate = totalCompleted.subtract(lastYearCompleted)
                                .divide(lastYearCompleted, 4, RoundingMode.HALF_UP)
                                .multiply(new BigDecimal("100"))
                                .setScale(2, RoundingMode.HALF_UP);
                        vo.setYoyRate(yoyRate);
                    }
                }

                resultList.add(vo);
            }
            else{
                GoodsTurnoverVO vo = new GoodsTurnoverVO();
                vo.setYear(targetYear);
                resultList.add(vo);
            }
        }

        return resultList;
    }

    @Override
    public List<TurnoverVO> getLatest6MonthsStats() {
        List<TurnoverVO> voList = new ArrayList<>();
        // 获取当前日期和6个月前的日期
        LocalDate currentDate = LocalDate.now();
        LocalDate sixMonthsAgo = currentDate.minusMonths(5); // 包含当前月，所以减5个月

        // 格式化日期
        DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyyMMdd");
        String startDateStr = sixMonthsAgo.format(formatter);
        String endDateStr = currentDate.format(formatter);

        System.out.println("查询日期范围: " + startDateStr + " - " + endDateStr);

        // 构建查询条件
        LambdaQueryWrapper<DryportProdoperTurnover> lqw = new LambdaQueryWrapper<>();


        lqw.eq(DryportProdoperTurnover::getOrgCode, "100360")
                .eq(DryportProdoperTurnover::getDelFlag, 0)
                .eq(DryportProdoperTurnover::getDateType,1)
                .ge(DryportProdoperTurnover::getStatisticTime, startDateStr)
                .le(DryportProdoperTurnover::getStatisticTime, endDateStr);

        // 执行查询
        List<DryportProdoperTurnover> entityList = dryportProdoperTurnoverMapper.selectList(lqw);

        // 将实体转换为VO
        if (entityList != null && !entityList.isEmpty()) {
            for(DryportProdoperTurnover entity : entityList) {
                TurnoverVO vo = new TurnoverVO();
                BeanUtil.copyProperties(entity, vo);
                vo.setTurnoverPlanned(entity.getTurnoverPlanned());
                vo.setTurnoverCompleted(entity.getTurnoverCompleted());

                if(entity.getTurnoverCompleted()!=null && entity.getTurnoverPlanned()!=null && entity.getTurnoverPlanned().compareTo(BigDecimal.ZERO)>0) {
                    vo.setCompletionRate(entity.getTurnoverCompleted()
                            .divide(entity.getTurnoverPlanned(), 2, BigDecimal.ROUND_HALF_UP).setScale(2, BigDecimal.ROUND_HALF_UP));
                } else {
                    vo.setCompletionRate(entity.getTurnoverCompleted());
                }


                voList.add(vo);
            }
        }


        List<TurnoverVO> sortedList = voList.stream()
                .sorted(Comparator.comparing(TurnoverVO::getYear)
                        .thenComparing(TurnoverVO::getMonth))
                .collect(Collectors.toList());
        return sortedList;


    }

}
